package main

import (
	"grpcTest/customer"
	"context"
	"strings"
	"net"
	"log"
	"google.golang.org/grpc"
)

const port = ":50051"

func main() {
	
	lis, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatal("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	customer.RegisterCustomerServer(s, &server{})
	s.Serve(lis)
	
}

type server struct {
	savedCustomers []*customer.CustomerRequest
}

func (s *server) CreateCustomer(ctx context.Context, in *customer.CustomerRequest) (*customer.CustomerResponse, error) {
	s.savedCustomers = append(s.savedCustomers, in)
	return &customer.CustomerResponse{Id:in.Id, Success:true}, nil
}

func (s *server) GetCustomers(filter *customer.CustomerFilter, stream customer.Customer_GetCustomersServer) error {
	for _, cs := range s.savedCustomers {
		if filter.Keyword != "" {
			if !strings.Contains(cs.Name, filter.Keyword) {
				continue
			}
		}
		if err := stream.Send(cs); err != nil {
			return err
		}
	}
	return nil
}